package postpc.powerreminders.com.ui.activities;

import postpc.powerreminders.com.db.RotgDatabase;
import postpc.powerreminders.com.location.RotgLocationManager;
import postpc.powerreminders.com.location.RotgLocationManager.LocationManagerCallback;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.nutiteq.BasicMapComponent;
import com.nutiteq.android.MapView;
import com.nutiteq.components.PlaceIcon;
import com.nutiteq.components.WgsPoint;
import com.nutiteq.location.LocationMarker;
import com.nutiteq.location.NutiteqLocationMarker;
import com.nutiteq.location.providers.AndroidGPSProvider;
import com.nutiteq.maps.CloudMade;
import com.nutiteq.ui.ThreadDrivenPanning;
import com.nutiteq.utils.Utils;
import com.nutiteq.wrappers.AppContext;

public class LocationEditActivity extends Activity {


	private static final String TAG = "LocationEditActivity";

	private String m_BSSID;
	private String m_SSID;
	private double m_Latitude = 35.196751;
	private double m_Longitude = 31.778569;
	private long m_ID;

	private MapView mapView;
	private BasicMapComponent mapComponent;
	private boolean onRetainCalled;

	private AndroidGPSProvider locationSource;

	private void updateBSSView() {
		TextView wifiView = (TextView)findViewById(postpc.powerreminders.com.R.id.location_edit_wifitext);
		Log.i(TAG, "BSSID = " + m_BSSID + "SSID = " + m_SSID);
		if (m_BSSID != null && m_BSSID.length() > 0 &&
				m_SSID  != null && m_SSID.length()  > 0) {
			wifiView.setText("WiFi location available (" + m_SSID +")");
		}
		else {
			wifiView.setText("WiFi location unavailable");
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(postpc.powerreminders.com.R.layout.location_edit);

		m_ID = getIntent().getLongExtra("id", -1);
		Log.d(TAG, "Got ID = " + m_ID);

		onRetainCalled = false;
		
		Button saveButton = (Button)findViewById(postpc.powerreminders.com.R.id.location_edit_savebutton);
		saveButton.setOnClickListener(new OnClickListener() {
	
			
			@Override
			public void onClick(View view) {
				Log.d(TAG, "Save button clicked");
				RotgDatabase db = RotgDatabase.getInstance();

				EditText nameEdit = (EditText)findViewById(postpc.powerreminders.com.R.id.location_edit_location_name);
				
				if (m_ID >= 0) {
					db.updateLocation(m_ID, nameEdit.getText().toString(), m_Longitude, m_Latitude, m_BSSID, m_SSID);
				} else {
					// Save current location
					WgsPoint point = locationSource.getLocation();
					if (point != null){
						m_Longitude = point.getLon();
						m_Latitude = point.getLat();
					}
					db.newLocation(nameEdit.getText().toString(), m_Longitude, m_Latitude, m_BSSID, m_SSID);
				}
				db.close();

				setResult(RESULT_OK);
				finish();
			}
		});
	
		// NEW OR NOT
		EditText nameEdit = (EditText)findViewById(postpc.powerreminders.com.R.id.location_edit_location_name);
		if (m_ID >= 0) {

			RotgDatabase db = RotgDatabase.getInstance();
			
			Cursor location = db.fetchLocation(m_ID);
			m_Longitude = location.getDouble(location.getColumnIndexOrThrow(RotgDatabase.GPS_LONGITUDE));
			m_Latitude = location.getDouble(location.getColumnIndexOrThrow(RotgDatabase.GPS_LATITUDE));
			
			mapComponent = new BasicMapComponent("091d584fced301b442654dd8c23b3fc94e765c31175c30.74326171", 
					new AppContext(this), 1, 1, 
					new WgsPoint(this.m_Longitude, this.m_Latitude), 22);
			mapComponent.setMap(new CloudMade("87babf4b9881457498ab1de3c3b79a05", "dorshaish", 64, 1));
			mapComponent.setPanningStrategy(new ThreadDrivenPanning());
			mapComponent.startMapping();
			
			mapView = (MapView)findViewById(postpc.powerreminders.com.R.id.location_edit_mapview);
			mapView.setMapComponent(mapComponent);
			
			m_BSSID = location.getString(location.getColumnIndexOrThrow(RotgDatabase.WIFI_MAC));
			m_SSID = location.getString(location.getColumnIndexOrThrow(RotgDatabase.WIFI_SSID));
			updateBSSView();
			nameEdit.setText(location.getString(location.getColumnIndexOrThrow(RotgDatabase.NAME)));

			location.close();
			db.close();
		}
		else {
			
			mapComponent = new BasicMapComponent("67c6a1e7ce56d3d6fa748ab6d9af3fd74e62294ae1fb53.14026705", 
					new AppContext(this), 1, 1, 
					new WgsPoint(this.m_Longitude, this.m_Latitude), 22);
			mapComponent.setMap(new CloudMade("87babf4b9881457498ab1de3c3b79a05", "dorshaish", 64, 1));
			mapComponent.setPanningStrategy(new ThreadDrivenPanning());
			mapComponent.startMapping();
			
			mapView = (MapView)findViewById(postpc.powerreminders.com.R.id.location_edit_mapview);
			mapView.setMapComponent(mapComponent);
			
			// Register for GPS Location   
			this.locationSource = new AndroidGPSProvider(
					(LocationManager) getSystemService(Context.LOCATION_SERVICE), 1000L);
			final LocationMarker marker = new NutiteqLocationMarker(new PlaceIcon(
					Utils.createImage("/res/drawable-hdpi/gpsmarker.png"), 5, 17), 3000, true);
			locationSource.setLocationMarker(marker);
			mapComponent.setLocationSource(locationSource);

			nameEdit.setText("");
			RotgLocationManager locationManager = RotgLocationManager.getInstance();
			locationManager.getLocation(new LocationManagerCallback() {

				@Override
				public void wifiInfoAvailable(String ssid, String bssid) {


					Log.d(TAG, "Got WIFI info: ssid='" + ssid + "' bssid='" + bssid + "'");


					if (ssid != null  && ssid.length() > 0 &&
							bssid != null && bssid.length() > 0) {
						m_BSSID = bssid;
						m_SSID = ssid;
					}

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							updateBSSView();
						}
					});


				}

				@Override
				public void gpsInfoAvailable(double lon, double lat) {
					m_Longitude = lon;
					m_Latitude = lat;

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							//updateMapView();
						}
					});
				}
			});

		}
	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		onRetainCalled = true;
		return mapComponent;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mapView != null) {
			mapView.clean();
			mapView = null;
		}

		if (!onRetainCalled) {
			mapComponent.stopMapping();
			mapComponent = null;
		}
	}
}
